import { ToastComponent, render as renderAmis } from 'amis';
import { useAsyncEffect, Layout, RadioGroup } from '@cscec/udp-ui';
import { useContext, useMemo } from 'react';
import { Empty } from 'antd';
import { getAmisEnv, schemaUtil } from '@/components/editor/util';
import { lowcodeWrapper } from '../common';
import { loadResource } from '@/components/editor/plugin';
import type { IStore } from './type';
import { DesignContext, type IDCtx } from '@/components/editor/context';
import React from 'react';

const global = window as any;

const radioGroupOptions = [
  { value: 'list', label: '列表' },
  { value: 'edit', label: '明细' },
];

function UILayout() {
  const { store, setStore } = useContext<IDCtx<IStore>>(DesignContext);

  useAsyncEffect(async () => {
    const result = schemaUtil.getData({ cache: true });
    const jsonSchema: any = result?.value?.jsonSchema || result?.value || {};
    await loadResource(result?.packages, false);
    setStore({
      loading: false, listInfo: jsonSchema.listInfo, editInfo: jsonSchema.editInfo, packages: result?.packages, session: 'preview',
    });
  }, []);

  const onActiveKeyChange = (activeKey: string) => {
    setStore({ activeKey });
  };

  const schemaValue = useMemo(() => (store.loading ? null : store[`${store.activeKey}Info`]), [store.loading, store.activeKey]);

  return (
    <Layout loading={store.loading} height="100%">
      <ToastComponent key="toast" position="top-right" />
      <Layout direction="row" center height={48} style={{ justifyContent: 'center', background: '#fff', borderBottom: '1px solid #e8e9eb' }}>
        <RadioGroup options={radioGroupOptions} value={store.activeKey} onChange={onActiveKeyChange} optionType="button" buttonStyle="solid" />
      </Layout>
      <Layout.Flex style={{pointerEvents: 'none'}}>
        {
                    schemaValue ? renderAmis(schemaValue, {
                      scopeRef: (amisScoped: any) => { global.amisScoped = amisScoped; },
                      style: { height: '100%' },
                      className: 'lowcode-view-root',
                    }, getAmisEnv('preview')) : <Empty style={{ marginTop: 100 }} />
                }
      </Layout.Flex>
    </Layout>

  );
}

export default lowcodeWrapper(UILayout, { isDesign: false });
